'use client';

import type { TBody, TMetadata } from '@/types';
import type { IOauthClientAuthCallbackBody, IToken } from '@/interfaces';
import { oauthClientAuthCallback } from '@/services/api';
import { useEffect } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useSearchParams } from 'next/navigation';
import LoadPage from '@/app/[locale]/load/load';
import useToast from '@/hooks/useToast';
import ErrorPage from '@/app/[locale]/error/error';
import { ColorModeItem } from '@/app/[locale]/navbar';
import { useTranslations } from 'use-intl';

export default function YwPage({ metadata }: { metadata: TMetadata }) {
  const urlSearchParams = useSearchParams();
  const { show } = useToast();
  const t = useTranslations('YwPage');

  const oauthClientAuthCallbackMutation = useMutation(
    async (variables: TBody<IOauthClientAuthCallbackBody>) => {
      try {
        return (await oauthClientAuthCallback(variables)) as IToken;
      } catch (e) {
        show({
          type: 'DANGER',
          message: e,
        });
        throw e;
      }
    },
  );

  useEffect(() => {
    if (
      urlSearchParams &&
      urlSearchParams.has('code') &&
      urlSearchParams.has('clientId')
    ) {
      const code = urlSearchParams.get('code')!.trim();
      const clientId = urlSearchParams.get('clientId')!.trim();
      const state = urlSearchParams.get('state')?.trim() ?? '';
      oauthClientAuthCallbackMutation.mutate({
        data: { code, state, clientId },
      });
    }
  }, []);

  useEffect(() => {
    if (oauthClientAuthCallbackMutation.data) {
      show({
        message: t('openAuthenticationAuthorizationCompleted'),
        type: 'SUCCESS',
      });

      setTimeout(() => {
        show({
          message: t('redirectToBeDone'),
          type: 'PRIMARY',
        });
      }, 1000);

      setTimeout(() => {
        location.href = '/';
      }, 1500);
    }
  }, [oauthClientAuthCallbackMutation.isLoading]);

  if (!urlSearchParams?.has('code') || !urlSearchParams?.has('clientId')) {
    return (
      <>
        <div className="col px-0 vh-100">
          <div className="card border-0 h-100">
            <div className="card-body align-items-center card-body d-flex justify-content-center text-center">
              <div>
                <h1 className="text-danger display-5">400 - BAD REQUEST</h1>
                <p className="lead">
                  {t(
                    'sorryAccessToThisResourceRequiresOpenAuthenticationAuthorization',
                  )}
                </p>

                <div className="hstack flex-wrap justify-content-center my-5 gap-4">
                  <a
                    href="/"
                    className="fw-bold text-primary text-decoration-none cursor-pointer"
                  >
                    <div className="border border-2 border-primary rounded-5 px-4 py-2 d-inline-block">
                      {t('returnToHomePage')}
                    </div>
                  </a>

                  <a
                    href="/login"
                    className="fw-bold text-primary text-decoration-none cursor-pointer"
                  >
                    <div className="border border-2 border-primary rounded-5 px-4 py-2 d-inline-block">
                      {t('returnToLoginPage')}
                    </div>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
        <ColorModeItem hidden={true} />
      </>
    );
  }

  if (oauthClientAuthCallbackMutation.data) {
    return (
      <>
        <div className="col px-0 vh-100">
          <div className="card border-0 h-100">
            <div className="card-body align-items-center card-body d-flex justify-content-center text-center">
              <div>
                <div className="mb-4 d-flex align-items-center justify-content-center">
                  <span
                    className="spinner-border me-2"
                    role="status"
                    aria-hidden="true"
                  ></span>
                  <span>{t('processingInProgress')}...</span>
                </div>
                <div className="text-muted">
                  {t('reminderProcessWillAutomaticallyRedirectUponCompletion')}
                </div>
              </div>
            </div>
          </div>
        </div>
        <ColorModeItem hidden={true} />
      </>
    );
  }

  if (oauthClientAuthCallbackMutation.error) {
    return <ErrorPage error={oauthClientAuthCallbackMutation.error} />;
  }

  return <LoadPage />;
}
